﻿KISSY.ready(function (S) {
    S.use("overlay, fgt/ui, validation, fgt/auth, js/rv-common", function (S, Overlay, UI, Validation, Auth, RVFunc) {
        var $ = S.all,
            J = jQuery,
            IMG_UPLOADER_QUEUE_SIZE_LIMIT = 2,
            popbox = UI.getPopbox(),
            imageUploadServer = CONFIG["imageUploadServer"],
            imageDownloadServer = CONFIG["imageDownloadServer"],
            imgCDNServer = CONFIG["imgCDNServer"],
            uploadify,
            photoList = $("#photo_list"),
            failureText = "Save failure, please try again later.";

        function savePhoto(photoId, RVId, photoUrl) {
            try {
                var paramStr = "photoId=" + photoId + "&RVId=" + RVId,
                    resultCode = FGT.core.constant.jsonResultCode,
                    delay = 1000;

                J.ajax({
                    url: "/rv/save/photo",
                    type: "POST",
                    data: paramStr,
                    success: function (data, textStatus, jqXHR) {
                        if (data.Result === resultCode.SUCCESS) {
                            photoList.prepend(data.Content);
                        }
                        else {
                            popbox.show(data.Content, delay);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        popbox.show(failureText, delay);
                    }
                });
            }
            catch (e) {
                popbox.show(failureText, delay);
            }
        }

        uploadify = J("#photo_upload").uploadify({
            "uploader": "/static/flash/uploadify.swf",
            "script": imageUploadServer,
            "buttonText": "Upload Image",
            "scriptAccess": "always",
            "queueID": "uploader_queue",
            "queueSizeLimit": IMG_UPLOADER_QUEUE_SIZE_LIMIT,
            "auto": true,
            "multi": true,
            "removeCompleted": false,
            "fileExt": "*.jpg;*.gif;*.png;*.jpeg",
            "scriptData": {
                "source": "1"
            },
            "onSelect": function (event, id, fileObj) {
                var target = J(event.target),
                    queue = $('#' + event.data.queueID);

                if (queue.children().length >= IMG_UPLOADER_QUEUE_SIZE_LIMIT) {
                    popbox.show('一次只能上传' + IMG_UPLOADER_QUEUE_SIZE_LIMIT + '张图片。', 1000);
                    return false;
                }

                var uploaderId = target.attr('id'),
                        queueItemId = uploaderId + id,
                        progressId = queueItemId + "ProgressBar";

                var queueItemStr = '<div id="' + queueItemId + '" class="uploader-item">'
                                                + '<div class="progress">'
                                                    + '<div id="' + progressId + '" class="progress-bar"></div>'
                                                + '</div>'
                                        + '</div>';

                J(queue).append(queueItemStr);
                return false;
            },
            "onError": function (event, id, fileObj, errorObj) {
                var target = J(event.target),
                        uploaderId = target.attr('id'),
                        queueItem = J("#" + uploaderId + id);

                queueItem.remove();
                popbox.show(failureText, 1000);
                return false;
            },
            "onProgress": function (event, id, fileObj, data) {
                var target = J(event.target),
                        uploaderId = target.attr('id'),
                        progress = J("#" + uploaderId + id + "ProgressBar");

                progress.animate({ 'width': data.percentage + '%' }, 250);
                return false;
            },
            "onQueueFull": function (event, queueSizeLimit) {
                popbox.show('一次只能上传' + queueSizeLimit + '张图片。', 1000);
                return false;
            },
            "onComplete": function (event, id, fileObj, response, data) {
                var target = J(event.target),
                        result = J.parseJSON(response),
                        resultCode = FGT.core.constant.jsonResultCode,
                        uploaderId = target.attr('id'),
                        queueItem = J("#" + uploaderId + id);

                if (result.Result === resultCode.SUCCESS) {
                    var ct = result.Content,
                        url = imageDownloadServer + "/d/1/" + ct.id + "(200x130).jpg";
                    savePhoto(ct.id, CONFIG["RVId"], url);

                }
                else {
                    popbox.show(failureText, 1000);
                }

                queueItem.remove();
                return false;
            }

        });

        /* delete & update photo */
        S.mix(RVFunc, {
            deletePhoto: function (photoId, RVId, target) {
                var $ = S.all,
                    photoListItemId;

                RVFunc._deletePhoto({
                    submitData: "photoid=" + photoId + "&rvid=" + RVId,
                    successCallback: function () {
                        photoListItemId = "#" + $(target).attr("data-photo-listitem-id");
                        $(photoListItemId).remove();
                    },
                    successCallBackContext: this,
                    successCallBackParams: undefined
                });
            },

            updatePhoto: function (photoId, RVId, target) {
                var $ = S.all,
                    textarea = $(target);

                RVFunc._updatePhoto({
                    submitData: "photoid=" + photoId + "&rvid=" + RVId + "&description=" + textarea.val(),
                    successCallback: function () {},
                    successCallBackContext: this,
                    successCallBackParams: undefined
                });
            }
        });



    });
});